/**
 * 2010(c) www.jcaramel.com
 * HINT
 * Places hint text on textboxes when content is empty
 * 
 * Requires:
 * 	jCaramel-Core
 */

jCaramel.hint = {
	
	/**
	 * Creates the hint object
	 * @param {jQuery} textbox to apply hint text
	 * @param {string} hint text to show
	 */
	_create: function(textbox, hint){
		
		//Create Handle
		jCaramel.createHandle(textbox);
		
		//Create label to apply hint
		var lbl = jQuery('<label>')
			.addClass('hint')
			.css('font-size', textbox.css('font-size'))
			.css('padding', (textbox.outerWidth() - textbox.innerWidth()) / 2);
		lbl.text(hint);
		
		//Create handle for hint label
		jCaramel.createHandle(lbl);
		
		//Relate label to text
		textbox.tag('hint', lbl.tag('handle'));
		
		//Relate text to label
		lbl.tag('textbox', textbox.tag('handle'));
		
		//Insert label next to the text
		lbl.insertAfter(textbox);
		
		//Show the hint
		jCaramel.hint.show(textbox);
		
		//Add handlers to textbox
		textbox.bind('focus', jCaramel.hint.textbox_Focus);
		textbox.bind('blur', jCaramel.hint.textbox_Blur);
		
		//Add handlers to lbl
		lbl.bind('click', jCaramel.hint.label_Click);
	},
	
	/**
	 * Gets the label containing the hint
	 * @param {jQuery} textbox
	 */
	getLabel: function(textbox){
		return jCaramel.getByHandle(textbox.tag('hint'));
	},
	
	/**
	 * Gets the textbox of the hint label
	 * @param {Object} label
	 */
	getTextbox: function(label){	
		return jCaramel.getByHandle(label.tag('textbox'))
	},
	
	/**
	 * Hides the hint
	 * @param {jQuery} textbox
	 */
	hide: function(textbox){
		jCaramel.hint.getLabel(textbox).hide();
	},
	
	/**
	 * Handles click on label
	 * @param {Object} evt
	 */
	label_Click: function(evt){
		jCaramel.hint.getTextbox(jQuery(this)).focus();
	},
	
	/**
	 * Shows the hint
	 * @param {jQuery} textbox
	 */
	show: function(textbox){
		
		var lbl = jCaramel.hint.getLabel(textbox);
		
		var offset = textbox.offset();
		
		lbl
			.css({ top: offset.top, left: offset.left })
			.width(textbox.width())
			.show();
	},
	
	/**
	 * Handles blur on textbox
	 * @param {Event} evt
	 */
	textbox_Blur: function(evt){
		var t = jQuery(this);
		
		if(t.val().length == 0){
			jCaramel.hint.show(t);
		}
	},
	
	/**
	 * Handles focus on textbox
	 * @param {Event} evt
	 */
	textbox_Focus: function(evt){
		var t = jQuery(this);
		
		jCaramel.hint.hide(t);
	},
	
};

/**
 * Shows the hint text when value is empty and not focused.
 * Only applies for textboxes (input type="text").
 * The hint text is shown by placing a LABEL element in front of the text
 * @param {Object} hint
 */
 jQuery.fn.hint = function(hint){
 	
	jCaramel.hint._create(this, hint);
	
	return this;
	
 };
